package com.demo.zhlg.service.impl;

import com.demo.zhlg.entity.Wallets;
import com.demo.zhlg.mapper.WalletsMapper;
import com.demo.zhlg.util.JwtUtil;
import com.demo.zhlg.util.Result;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import com.demo.zhlg.entity.Users;
import com.demo.zhlg.mapper.UsersMapper;
import com.demo.zhlg.service.UsersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.sqlite.date.DateFormatUtils;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;

import static com.demo.zhlg.entity.table.UsersTableDef.USERS;

/**
 *  服务层实现。
 *
 * @author lenovo
 * @since 2025-04-26
 */
@Service
public class UsersServiceImpl extends ServiceImpl<UsersMapper, Users> implements UsersService {
    @Autowired
    private UsersMapper usersMapper;

    @Autowired
    private WalletsMapper walletsMapper;

    @Autowired
    private AuthenticationManager authenticationManager;

    private int getUserId() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        return loginUser.getUser().getUserId();
    }

    @Override
    public Object login(Users users) {
        UsernamePasswordAuthenticationToken authenticationToken  =
                new UsernamePasswordAuthenticationToken(users.getUsername(), users.getPassword());
        Authentication auth = authenticationManager.authenticate(authenticationToken);
        LoginUser loginUser = (LoginUser) auth.getPrincipal();
        Users ret = loginUser.getUser();
        ret.setPassword(JwtUtil.generateToken(ret));
        return Result.success(ret);
    }

    @Override
    public Object register(Users user) {
        if(usersMapper.selectOneByQuery(new QueryWrapper()
                .where(USERS.PHONE.eq(user.getPhone()))) != null){
            return Result.fail("手机号已被注册");
        }
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        user.setPassword(encoder.encode(user.getPassword()));
        user.setRegisterTime(DateFormatUtils.format(new Date(),"yyyy-MM-dd HH:mm:ss"));
        user.setUpdateTime(DateFormatUtils.format(new Date(),"yyyy-MM-dd HH:mm:ss"));
        user.setCreateTime(DateFormatUtils.format(new Date(),"yyyy-MM-dd HH:mm:ss"));
        usersMapper.insert(user);
        user = usersMapper.selectOneByQuery(new QueryWrapper().where(USERS.USERNAME.eq(user.getUsername())));
        Wallets wallet = new Wallets();
        wallet.setUserId(user.getUserId());
        wallet.setBalance(5000.0);
        wallet.setFrozenBalance(0.0);
        wallet.setTotalIncome(0.0);
        wallet.setTotalWithdraw(0.0);
        wallet.setFrozenBalance(0.0);
        wallet.setWalletStatus(0);
        wallet.setCreateTime(DateFormatUtils.format(new Date(),"yyyy-MM-dd HH:mm:ss"));
        wallet.setUpdateTime(DateFormatUtils.format(new Date(),"yyyy-MM-dd HH:mm:ss"));
        walletsMapper.insert(wallet);
        return Result.success("注册成功");
    }

    @Override
    public Object checkLog() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        Users ret = loginUser.getUser();
        ret.setPassword(JwtUtil.generateToken(ret));
        return Result.success(ret);
    }

    @Override
    public Object getInfo() {
        Users user = usersMapper.selectOneById(getUserId());
        user.setAvatar(null);
        return Result.success(user);
    }

    @Override
    public Object forgotPassword(Users user) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper
                .where(USERS.PHONE.eq(user.getPhone()));
        user.setUserId(usersMapper.selectOneByQuery(queryWrapper).getUserId());
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        user.setPassword(encoder.encode(user.getPassword()));
        return Result.success(usersMapper.update(user));
    }

    @Override
    public Object uploadAvatar(MultipartFile file) {
        if (file.isEmpty()) {
            return Result.fail("请选择文件");
        }

        try {
            // 获取当前登录用户ID
            Long userId = (long)getUserId();

            // 获取文件二进制数据
            byte[] avatarBytes = file.getBytes();

            // 更新用户头像信息到数据库
            Users user = new Users();
            user.setUserId(userId.intValue());
            user.setAvatar(avatarBytes); // 直接存储二进制数据
            user.setUpdateTime(DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
            usersMapper.update(user);

            return Result.success(user.getAvatar());
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail("上传失败：" + e.getMessage());
        }
    }

    @Override
    public Object getAvatar() {
        try {
            // 获取当前登录用户ID
            Long userId = (long)getUserId();

            // 从数据库获取用户头像二进制数据
            byte[] avatarData = usersMapper.selectOneById(userId).getAvatar();

            if (avatarData == null || avatarData.length == 0) {
                return Result.fail("未找到头像");
            }

            // 将二进制数据转为Base64编码返回
            String base64Avatar = Base64.getEncoder().encodeToString(avatarData);

            Map<String, String> data = new HashMap<>();
            data.put("avatarData", "data:image/jpeg;base64," + base64Avatar); // 添加前缀以便前端直接使用

            return Result.success(data);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail("获取头像失败：" + e.getMessage());
        }
    }

    @Override
    public Object getAvatarById(Integer id) {
        try {
            // 获取当前登录用户ID
            Long userId = (long)id;

            // 从数据库获取用户头像二进制数据
            byte[] avatarData = usersMapper.selectOneById(userId).getAvatar();

            if (avatarData == null || avatarData.length == 0) {
                return Result.fail("未找到头像");
            }

            // 将二进制数据转为Base64编码返回
            String base64Avatar = Base64.getEncoder().encodeToString(avatarData);

            Map<String, String> data = new HashMap<>();
            data.put("avatarData", "data:image/jpeg;base64," + base64Avatar); // 添加前缀以便前端直接使用

            return Result.success(data);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail("获取头像失败：" + e.getMessage());
        }
    }
}
